package util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class RedisUtil {

    // 简易连接池及工具
    private static JedisPool jedisPool;
    private static Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .create();
    static {
        InputStream is = RedisUtil.class.getClassLoader().getResourceAsStream("redis.properties");
        Properties pro = new Properties();
        try {
            pro.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建Jedis配置对象
        JedisPoolConfig config = new JedisPoolConfig();
        config.setTestOnBorrow(true);
        config.setBlockWhenExhausted(true);
        config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
        config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
        config.setMaxWaitMillis(Integer.parseInt(pro.getProperty("maxWaitMillis")));

        // 初始化
        jedisPool = new JedisPool(config,pro.getProperty("host"),
                Integer.parseInt(pro.getProperty("port")));
    }

    // 获取连接
    public static Jedis getJedis()
    {
        return jedisPool.getResource();
    }

    /**
     * 获取数据
     * @param key
     * @param cla
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T getSource (String key, Class<T> cla) throws Exception{
        Jedis jedis = null;
        try {
            jedis = getJedis();
            String jsonValue = jedis.get(key);
            if (jsonValue == null) {
                return null;
            }
            return gson.fromJson(jsonValue, cla);
        } catch (Exception e) {
            throw e;
        } finally {
            jedis.close();
        }
    }

    /**
     * 添加数据设置超时时间
     * @param key 键
     * @param value 值
     * @param expire 超时时间
     * @throws Exception
     */
    public static void set(String key, Object value,int expire) throws Exception {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.set(key, gson.toJson(value));
            // 设置超时时间
            if(expire > 0) {
                jedis.expire(key, expire);
            }
        } catch (Exception e) {
            throw  e;
        } finally {
            jedis.close();
        }
    }


}
